package com.teamwe.movecard.util;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.codehaus.xfire.util.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;

@Slf4j
@Component
public class WxTool {
    //微信小程序appId
    private static String APP_ID;
    //微信小程序私钥
    private static String APP_SECRET ;

    private static RestTemplate restTemplate;


    /***
     * 从服务端
     * @param js_code
     * @return
     */
    public static String getSessionKey(String js_code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + APP_ID + "&secret="
                + APP_SECRET + "&js_code=" + js_code + "&grant_type=authorization_code";
        String reusult = restTemplate.getForObject(url, String.class);
        JSONObject oppidObj = JSONObject.parseObject(reusult);
        String openid = (String) oppidObj.get("openid");
        log.info("获取到的openId为："+ openid);
        String session_key = (String) oppidObj.get("session_key");
        return session_key;
    }

    /**
     * 获取信息
     */
    public static JSONObject getUserInfo(String encryptedData,String sessionkey,String iv) throws Exception {
        // 被加密的数据
        byte[] dataByte = Base64.decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.decode(sessionkey);
        // 偏移量
        byte[] ivByte = Base64.decode(iv);
        // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
        int base = 16;
        if (keyByte.length % base != 0) {
            byte[] temp = new byte[base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
            keyByte = temp;
        }
        // 初始化
        Security.addProvider(new BouncyCastleProvider());
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding","BC");
        SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
        AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
        parameters.init(new IvParameterSpec(ivByte));
        cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
        byte[] resultByte = cipher.doFinal(dataByte);
        if (null != resultByte && resultByte.length > 0) {
            String result = new String(resultByte, "UTF-8");
//                return new ObjectMapper().readValue(result, User.class);
            return JSONObject.parseObject(result);
        }
        return null;
    }
    @Value("${wx.APP_ID}")
    public void setAppId(String appId) {
        APP_ID = appId;
    }
    @Value("${wx.APP_SECRET}")
    public void setAppSecret(String appSecret) {
        APP_SECRET = appSecret;
    }
    @Autowired
    public void setRestTemplate(RestTemplate restTemplate) {
        WxTool.restTemplate = restTemplate;
    }
}
